package exercise

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/exercise"
	exerciseReq "github.com/flipped-aurora/gin-vue-admin/server/model/exercise/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/interviewType"
	"github.com/flipped-aurora/gin-vue-admin/server/model/power"
)

type ExercisesService struct {
}

// CreateExercises 创建exercise表记录
// Author [piexlmax](https://github.com/piexlmax)
func (exercisesService *ExercisesService) CreateExercises(exercises *exercise.Exercises) (err error) {
	err = global.GVA_DB.Create(exercises).Error
	return err
}

// DeleteExercises 删除exercise表记录
// Author [piexlmax](https://github.com/piexlmax)
func (exercisesService *ExercisesService) DeleteExercises(exercises exercise.Exercises) (err error) {
	err = global.GVA_DB.Delete(&exercises).Error
	return err
}

// DeleteExercisesByIds 批量删除exercise表记录
// Author [piexlmax](https://github.com/piexlmax)
func (exercisesService *ExercisesService) DeleteExercisesByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]exercise.Exercises{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateExercises 更新exercise表记录
// Author [piexlmax](https://github.com/piexlmax)
func (exercisesService *ExercisesService) UpdateExercises(exercises exercise.Exercises2) (err error) {
	var interview power.Interview
	dbsearch := global.GVA_DB.Model(&power.Interview{})
	err = dbsearch.Where("id=?", exercises.Interviewid).First(&interview).Error
	if err != nil {
		return err
	}
	var exInfo []exercise.Exercises
	db := global.GVA_DB.Model(&exercise.Exercises{})
	err = db.Where("userid=? and interviewid = ?", exercises.UserID, interview.ID).Find(&exInfo).Error
	if err != nil {
		return err
	}
	if len(exInfo) == 0 {
		interviewid := int(interview.ID)
		db.Create(&exercise.Exercises{
			Interviewid: &interviewid,
			Isok:        &exercises.Isok,
			LevelId1:    interview.Level1,
			LevelId2:    interview.Level2,
			LevelId3:    interview.Level3,
			Userid:      &exercises.UserID,
		})
		return nil
	}
	return db.Where("userid=? and interviewid = ?", exercises.UserID, interview.ID).Update("isok", exercises.Isok).Error
}

// GetExercises 根据id获取exercise表记录
// Author [piexlmax](https://github.com/piexlmax)
func (exercisesService *ExercisesService) GetExercises(id uint) (exercises exercise.Exercises, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&exercises).Error
	return
}

// GetExercisesInfoList 分页获取exercise表记录
// Author [piexlmax](https://github.com/piexlmax)
func (exercisesService *ExercisesService) GetExercisesInfoList(info exerciseReq.ExercisesSearch) (list []exercise.Exercises2, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&exercise.Exercises{})
	var exercisess []exercise.Exercises
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Userid != nil {
		db = db.Where("userid = ?", info.Userid)
	}
	err = db.Find(&exercisess).Error
	if err != nil {
		return nil, 0, err
	}

	exercisesMap := map[uint]exercise.Exercises{}
	for _, val := range exercisess {
		exercisesMap[uint(*val.Interviewid)] = val
	}

	dbEs := global.GVA_DB.Model(&power.Interview{})
	var esInterviews []power.Interview

	err = dbEs.Count(&total).Error
	if err != nil {
		return
	}
	if info.LevelId1 != nil {
		dbEs = dbEs.Where("level1 = ?", *info.LevelId1)
	}
	if info.LevelId2 != nil {
		dbEs = dbEs.Where("level2 = ?", *info.LevelId2)
	}
	if info.LevelId3 != nil {
		dbEs = dbEs.Where("level3 = ?", *info.LevelId3)
	}

	err = dbEs.Order("priority desc").Limit(limit).Offset(offset).Find(&esInterviews).Error
	if err != nil {
		return
	}
	var typeIDs []int
	for _, val := range esInterviews {
		if val.Level1 != nil {
			typeIDs = append(typeIDs, *val.Level1)
		}

		if val.Level2 != nil {
			typeIDs = append(typeIDs, *val.Level2)
		}

		if val.Level3 != nil {
			typeIDs = append(typeIDs, *val.Level3)
		}
	}
	var typeInfos []interviewType.InterviewType
	err = global.GVA_DB.Where("id in(?)", typeIDs).Find(&typeInfos).Error
	if err != nil {
		return nil, 0, err
	}
	typeMap := map[uint]interviewType.InterviewType{}
	for _, val := range typeInfos {
		typeMap[val.ID] = val
	}
	var res []exercise.Exercises2
	for _, val := range esInterviews {
		isOk := 0
		exInfo, ok := exercisesMap[val.ID]
		if ok {
			isOk = *exInfo.Isok
		}
		leval1 := "未知"
		if val.Level1 != nil {
			level1Info, ok := typeMap[uint(*val.Level1)]
			if ok {
				leval1 = level1Info.Name
			}
		}

		leval2 := "未知"
		if val.Level2 != nil {
			level2Info, ok := typeMap[uint(*val.Level2)]
			if ok {
				leval2 = level2Info.Name
			}
		}
		leval3 := "未知"
		if val.Level3 != nil {
			level3Info, ok := typeMap[uint(*val.Level3)]
			if ok {
				leval3 = level3Info.Name
			}
		}

		res = append(res, exercise.Exercises2{
			Interviewid:     val.ID,
			InterviewTitles: val.InterviewTitle,
			Answer:          val.Answer,
			Isok:            isOk,
			Level1:          leval1,
			Level2:          leval2,
			Level3:          leval3,
		})
	}
	return res, total, err
}
